package com.chat;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

public class Chat extends JFrame {
	private JScrollPane scrollPane = null;
	private TextPaneMenu text = null;
	private Box box = null; // 放输入组件的容器
	private JButton b_insert = null, b_remove = null, b_file = null; // 插入按钮;清除按钮;插入图片按钮
	private TextAreaMenu addText = null; // 文字输入框
	private JComboBox fontName = null, fontSize = null, 
			fontStyle = null, fontColor = null, fontBackColor = null; // 字体名称;字号大小;文字样式;文字颜色;文字背景颜色

	private StyledDocument doc = null;

	public Chat() {
		super("JTextPane Test");
		try { // 使用Windows的界面风格
			UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
		} catch (Exception e) {
			e.printStackTrace();
		}

		text = new TextPaneMenu();
		text.setEditable(false);
		text.setBackground(new Color(200, 227, 189));//默认淡绿
		doc = text.getStyledDocument(); // 获得JTextPane的Document
		scrollPane = new JScrollPane(text);
		scrollPane.setPreferredSize(new Dimension(400, 400));
		addText = new TextAreaMenu();
		String[] str_name = { "宋体", "黑体", "Dialog", "Gulim" };
		String[] str_Size = { "14", "18", "22", "30", "40" };
		String[] str_Style = { "常规", "斜体", "粗体", "粗斜体" };
		String[] str_Color = { "黑色", "红色", "蓝色", "白色", "绿色" };
		String[] str_BackColor = { "淡绿", "灰色", "白色", "淡蓝", "淡黄"};
		fontName = new JComboBox(str_name); // 字体名称
		fontSize = new JComboBox(str_Size); // 字号
		fontStyle = new JComboBox(str_Style); // 样式
		fontColor = new JComboBox(str_Color); // 颜色
		fontBackColor = new JComboBox(str_BackColor); // 背景颜色
		b_insert = new JButton("发送"); // 插入
		b_remove = new JButton("清空"); // 清除
		b_file = new JButton("文件"); 
		
		
		
		fontBackColor.addItemListener(new ItemListener() {
			
			@Override
			public void itemStateChanged(ItemEvent e) {
				// TODO Auto-generated method stub
				if(e.getStateChange()==ItemEvent.SELECTED){
					String backColor = (String)e.getItem();
					
						if (backColor.equals("白色")) {
							text.setBackground(new Color(255, 255, 255));
						} else if (backColor.equals("灰色")) {
							text.setBackground(new Color(200, 200, 200));
						} else if (backColor.equals("淡绿")) {
							text.setBackground(new Color(200, 227, 189));
						} else if (backColor.equals("淡蓝")) {
							text.setBackground(new Color(186, 209, 247));
						} else if (backColor.equals("淡黄")) {
							text.setBackground(new Color(242, 236, 221));
						}
					
				}
				
			}
		});
		/*b_insert.addActionListener(new ActionListener() { // 插入文字的事件
			public void actionPerformed(ActionEvent e) {
				insert(getFontAttrib());
				addText.setText("");
			}
		});*/

		b_remove.addActionListener(new ActionListener() { // 清除事件
			public void actionPerformed(ActionEvent e) {
				text.setText("");
			}
		});

		/*b_file.addActionListener(new ActionListener() { // 插入图片事件
			public void actionPerformed(ActionEvent arg0) {
				JFileChooser f = new JFileChooser(); // 查找文件
				f.showOpenDialog(null);
				insertIcon(f.getSelectedFile()); // 插入图片
			}
		});*/
		
		box = Box.createVerticalBox(); // 竖结构
		Box box_1 = Box.createHorizontalBox(); // 横结构
		Box box_2 = Box.createHorizontalBox(); // 横结构
		box_2.setPreferredSize(new Dimension(box.getWidth(), 100));//设置大小
		box.add(box_1);
		box.add(Box.createVerticalStrut(8)); // 两行的间距
		box.add(box_2);
		box.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8)); // 8个的边距
		// 开始将所需组件加入容器

		box_1.add(new JLabel("字体：")); // 加入标签
		box_1.add(fontName); // 加入组件
		box_1.add(Box.createHorizontalStrut(8)); // 间距
		box_1.add(new JLabel("样式："));
		box_1.add(fontStyle);
		box_1.add(Box.createHorizontalStrut(8));
		box_1.add(new JLabel("字号："));
		box_1.add(fontSize);
		box_1.add(Box.createHorizontalStrut(8));
		box_1.add(new JLabel("颜色："));
		box_1.add(fontColor);
		box_1.add(Box.createHorizontalStrut(8));
		box_1.add(new JLabel("背景："));
		box_1.add(fontBackColor);
		box_1.add(Box.createHorizontalStrut(8));
		box_1.add(b_file);
		box_2.add(addText);
		box_2.add(Box.createHorizontalStrut(8));
		box_2.add(b_insert);
		box_2.add(Box.createHorizontalStrut(8));
		box_2.add(b_remove);
		//this.getRootPane().setDefaultButton(b_insert); // 默认回车按钮
		this.getContentPane().add(scrollPane);
		this.getContentPane().add(box, BorderLayout.SOUTH);
		this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
		//this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		// 更改JFrame的图标：
	
		this.setIconImage(Toolkit.getDefaultToolkit().getImage(
				this.getClass().getResource("/resource/2.png")));
		
		pack();
		this.setLocationRelativeTo(null);
		this.setVisible(true);
		addText.requestFocus();
	}

	/*private void insertIcon(File file) {
		text.setCaretPosition(doc.getLength()); // 设置插入位置
		text.insertIcon(new ImageIcon(file.getPath())); // 插入图片
		insert(new FontAttrib()); // 这样做可以换行
	}*/

	/*private void insert(FontAttrib attrib) {
		try { // 插入文本
			doc.insertString(doc.getLength(), attrib.getText() + "\n", attrib.getAttrSet());
		} catch (BadLocationException e) {
			e.printStackTrace();
		}
	}*/

	public FontAttrib getFontAttrib() {
		FontAttrib att = new FontAttrib();
		att.setText(addText.getText());//内容
		att.setName((String) fontName.getSelectedItem());//字体
		att.setSize(Integer.parseInt((String) fontSize.getSelectedItem()));//大小
		String temp_style = (String) fontStyle.getSelectedItem();
		if (temp_style.equals("常规")) {
			att.setStyle(FontAttrib.GENERAL);
		} else if (temp_style.equals("粗体")) {
			att.setStyle(FontAttrib.BOLD);
		} else if (temp_style.equals("斜体")) {
			att.setStyle(FontAttrib.ITALIC);
		} else if (temp_style.equals("粗斜体")) {
			att.setStyle(FontAttrib.BOLD_ITALIC);
		}
		String temp_color = (String) fontColor.getSelectedItem();
		if (temp_color.equals("黑色")) {
			att.setColor(new Color(0, 0, 0));
		} else if (temp_color.equals("红色")) {
			att.setColor(new Color(255, 0, 0));
		} else if (temp_color.equals("蓝色")) {
			att.setColor(new Color(0, 0, 255));
		} else if (temp_color.equals("白色")) {
			att.setColor(new Color(255, 255, 255));
		} else if (temp_color.equals("绿色")) {
			att.setColor(new Color(0, 255, 0));
		}
		/*String temp_backColor = (String) fontBackColor.getSelectedItem();
		if (!temp_backColor.equals("无色")) {
			if (temp_backColor.equals("灰色")) {
				att.setBackColor(new Color(200, 200, 200));
			} else if (temp_backColor.equals("淡红")) {
				att.setBackColor(new Color(255, 200, 200));
			} else if (temp_backColor.equals("淡蓝")) {
				att.setBackColor(new Color(200, 200, 255));
			} else if (temp_backColor.equals("淡黄")) {
				att.setBackColor(new Color(255, 255, 200));
			} else if (temp_backColor.equals("淡绿")) {
				att.setBackColor(new Color(200, 255, 200));
			}
		}*/
		return att;
	}

	/*public static void main(String args[]) {
		new Chat();
	}*/
	
	
	
	public JScrollPane getScrollPane() {
		return scrollPane;
	}

	public void setScrollPane(JScrollPane scrollPane) {
		this.scrollPane = scrollPane;
	}

	public TextPaneMenu getText() {
		return text;
	}

	public void setText(TextPaneMenu text) {
		this.text = text;
	}

	public Box getBox() {
		return box;
	}

	public void setBox(Box box) {
		this.box = box;
	}

	public JButton getB_insert() {
		return b_insert;
	}

	public void setB_insert(JButton b_insert) {
		this.b_insert = b_insert;
	}

	public JButton getB_remove() {
		return b_remove;
	}

	public void setB_remove(JButton b_remove) {
		this.b_remove = b_remove;
	}

	
	public JButton getB_file() {
		return b_file;
	}

	public void setB_file(JButton b_file) {
		this.b_file = b_file;
	}

	public TextAreaMenu getAddText() {
		return addText;
	}

	public void setAddText(TextAreaMenu addText) {
		this.addText = addText;
	}

	public JComboBox getFontName() {
		return fontName;
	}

	public void setFontName(JComboBox fontName) {
		this.fontName = fontName;
	}

	public JComboBox getFontSize() {
		return fontSize;
	}

	public void setFontSize(JComboBox fontSize) {
		this.fontSize = fontSize;
	}

	public JComboBox getFontStyle() {
		return fontStyle;
	}

	public void setFontStyle(JComboBox fontStyle) {
		this.fontStyle = fontStyle;
	}

	public JComboBox getFontColor() {
		return fontColor;
	}

	public void setFontColor(JComboBox fontColor) {
		this.fontColor = fontColor;
	}

	public JComboBox getFontBackColor() {
		return fontBackColor;
	}

	public void setFontBackColor(JComboBox fontBackColor) {
		this.fontBackColor = fontBackColor;
	}

	public StyledDocument getDoc() {
		return doc;
	}

	public void setDoc(StyledDocument doc) {
		this.doc = doc;
	}








	 class FontAttrib {
		public static final int GENERAL = 0; // 常规
		public static final int BOLD = 1; // 粗体
		public static final int ITALIC = 2; // 斜体
		public static final int BOLD_ITALIC = 3; // 粗斜体
		private SimpleAttributeSet attrSet = null; // 属性集
		private String text = null, name = null; // 要输入的文本和字体名称
		private int style = 0, size = 0; // 样式和字号
		private Color color = null; // 文字颜色

		public FontAttrib() {
		}

		public SimpleAttributeSet getAttrSet() {
			attrSet = new SimpleAttributeSet();
			if (name != null) {
				StyleConstants.setFontFamily(attrSet, name);
			}
			if (style == FontAttrib.GENERAL) {
				StyleConstants.setBold(attrSet, false);
				StyleConstants.setItalic(attrSet, false);
			} else if (style == FontAttrib.BOLD) {
				StyleConstants.setBold(attrSet, true);
				StyleConstants.setItalic(attrSet, false);
			} else if (style == FontAttrib.ITALIC) {
				StyleConstants.setBold(attrSet, false);
				StyleConstants.setItalic(attrSet, true);
			} else if (style == FontAttrib.BOLD_ITALIC) {
				StyleConstants.setBold(attrSet, true);
				StyleConstants.setItalic(attrSet, true);
			}
			StyleConstants.setFontSize(attrSet, size);
			if (color != null) {
				StyleConstants.setForeground(attrSet, color);
			}
			
			return attrSet;
		}
		//接受到的消息，默认样式
		public SimpleAttributeSet getDefaultAttrSet(){
			attrSet = new SimpleAttributeSet();
			StyleConstants.setFontFamily(attrSet, "宋体");
			StyleConstants.setFontSize(attrSet, 14);
			return attrSet;
		}
		
		//接受到的消息，默认样式
		public SimpleAttributeSet getUserAttrSet(){
			attrSet = new SimpleAttributeSet();
			StyleConstants.setFontFamily(attrSet, "黑体");
			StyleConstants.setFontSize(attrSet, 14);
			StyleConstants.setForeground(attrSet, new Color(153, 153, 153));
			return attrSet;
		}
		
		public void setAttrSet(SimpleAttributeSet attrSet) {
			this.attrSet = attrSet;
		}

		public String getText() {
			return text;
		}

		public void setText(String text) {
			this.text = text;
		}

		public Color getColor() {
			return color;
		}

		public void setColor(Color color) {
			this.color = color;
		}

		
		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public int getSize() {
			return size;
		}

		public void setSize(int size) {
			this.size = size;
		}

		public int getStyle() {
			return style;
		}

		public void setStyle(int style) {
			this.style = style;
		}
	}
	
	
	
	/**
	 * 带有功能菜单的JTextArea
	 * 内部类
	 */
	class TextAreaMenu extends JTextArea implements MouseListener {

		private static final long serialVersionUID = -2308615404205560110L;

		private JPopupMenu pop = null; // 弹出菜单

		private JMenuItem copy = null, paste = null, cut = null; // 三个功能菜单

		public TextAreaMenu() {
			super();
			init();
		}

		private void init() {
			this.addMouseListener(this);
			pop = new JPopupMenu();
			pop.add(copy = new JMenuItem("复制"));
			pop.add(paste = new JMenuItem("粘贴"));
			pop.add(cut = new JMenuItem("剪切"));
			copy.setAccelerator(KeyStroke.getKeyStroke('C', InputEvent.CTRL_MASK));
			paste.setAccelerator(KeyStroke.getKeyStroke('V', InputEvent.CTRL_MASK));
			cut.setAccelerator(KeyStroke.getKeyStroke('X', InputEvent.CTRL_MASK));
			copy.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					action(e);
				}
			});
			paste.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					action(e);
				}
			});
			cut.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					action(e);
				}
			});
			this.add(pop);
		}

		/**
		 * 菜单动作
		 * 
		 * @param e
		 */
		public void action(ActionEvent e) {
			String str = e.getActionCommand();
			if (str.equals(copy.getText())) { // 复制
				this.copy();
			} else if (str.equals(paste.getText())) { // 粘贴
				this.paste();
			} else if (str.equals(cut.getText())) { // 剪切
				this.cut();
			}
		}

		public JPopupMenu getPop() {
			return pop;
		}

		public void setPop(JPopupMenu pop) {
			this.pop = pop;
		}

		/**
		 * 剪切板中是否有文本数据可供粘贴
		 * 
		 * @return true为有文本数据
		 */
		public boolean isClipboardString() {
			boolean b = false;
			Clipboard clipboard = this.getToolkit().getSystemClipboard();
			Transferable content = clipboard.getContents(this);
			try {
				if (content.getTransferData(DataFlavor.stringFlavor) instanceof String) {
					b = true;
				}
			} catch (Exception e) {
			}
			return b;
		}

		/**
		 * 文本组件中是否具备复制的条件
		 * 
		 * @return true为具备
		 */
		public boolean isCanCopy() {
			boolean b = false;
			int start = this.getSelectionStart();
			int end = this.getSelectionEnd();
			if (start != end)
				b = true;
			return b;
		}

		public void mouseClicked(MouseEvent e) {
		}

		public void mouseEntered(MouseEvent e) {
		}

		public void mouseExited(MouseEvent e) {
		}

		public void mousePressed(MouseEvent e) {
			if (e.getButton() == MouseEvent.BUTTON3) {
				copy.setEnabled(isCanCopy());
				paste.setEnabled(isClipboardString());
				cut.setEnabled(isCanCopy());
				pop.show(this, e.getX(), e.getY());
			}
		}

		public void mouseReleased(MouseEvent e) {
		}

	}
	
	/**
	 * 带有功能菜单的JTextPane
	 * 内部类
	 */
	class TextPaneMenu extends JTextPane implements MouseListener {

		private static final long serialVersionUID = -2308615404205560112L;

		private JPopupMenu pop = null; // 弹出菜单

		private JMenuItem copy = null, paste = null, cut = null; // 三个功能菜单

		public TextPaneMenu() {
			super();
			init();
		}

		private void init() {
			this.addMouseListener(this);
			pop = new JPopupMenu();
			pop.add(copy = new JMenuItem("复制"));
			pop.add(paste = new JMenuItem("粘贴"));
			pop.add(cut = new JMenuItem("剪切"));
			copy.setAccelerator(KeyStroke.getKeyStroke('C', InputEvent.CTRL_MASK));
			paste.setAccelerator(KeyStroke.getKeyStroke('V', InputEvent.CTRL_MASK));
			cut.setAccelerator(KeyStroke.getKeyStroke('X', InputEvent.CTRL_MASK));
			copy.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					action(e);
				}
			});
			paste.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					action(e);
				}
			});
			cut.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					action(e);
				}
			});
			this.add(pop);
		}

		/**
		 * 菜单动作
		 * 
		 * @param e
		 */
		public void action(ActionEvent e) {
			String str = e.getActionCommand();
			if (str.equals(copy.getText())) { // 复制
				this.copy();
			} else if (str.equals(paste.getText())) { // 粘贴
				this.paste();
			} else if (str.equals(cut.getText())) { // 剪切
				this.cut();
			}
		}

		public JPopupMenu getPop() {
			return pop;
		}

		public void setPop(JPopupMenu pop) {
			this.pop = pop;
		}

		/**
		 * 剪切板中是否有文本数据可供粘贴
		 * 
		 * @return true为有文本数据
		 */
		public boolean isClipboardString() {
			boolean b = false;
			Clipboard clipboard = this.getToolkit().getSystemClipboard();
			Transferable content = clipboard.getContents(this);
			try {
				if (content.getTransferData(DataFlavor.stringFlavor) instanceof String) {
					b = true;
				}
			} catch (Exception e) {
			}
			return b;
		}

		/**
		 * 文本组件中是否具备复制的条件
		 * 
		 * @return true为具备
		 */
		public boolean isCanCopy() {
			boolean b = false;
			int start = this.getSelectionStart();
			int end = this.getSelectionEnd();
			if (start != end)
				b = true;
			return b;
		}

		public void mouseClicked(MouseEvent e) {
		}

		public void mouseEntered(MouseEvent e) {
		}

		public void mouseExited(MouseEvent e) {
		}

		public void mousePressed(MouseEvent e) {
			if (e.getButton() == MouseEvent.BUTTON3) {
				copy.setEnabled(isCanCopy());
				paste.setEnabled(isClipboardString());
				cut.setEnabled(isCanCopy());
				pop.show(this, e.getX(), e.getY());
			}
		}

		public void mouseReleased(MouseEvent e) {
		}

	}
	
}
